package com.magupe.netty.im.client.boot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.magupe.netty.im.client.handler.HelloClientHandlerAdapter;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyImClient {

protected Logger logger = LoggerFactory.getLogger(NettyImClient.class);
	
	private static final int MAX_RETRY = 3;
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 7000;
    
	Channel channel;
	
	NettyImClient(){

	}
	
	protected void init() {
    	NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    	
    	Bootstrap bootstrap = new Bootstrap();
        bootstrap
	        .group(workerGroup)
	        .channel(NioSocketChannel.class)
	        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
	        .option(ChannelOption.SO_KEEPALIVE, true)
	        .option(ChannelOption.TCP_NODELAY, true)
	        .handler(new ChannelInitializer<SocketChannel>() {
	            @Override
	            public void initChannel(SocketChannel ch) {
	            	ch.pipeline().addLast(new HelloClientHandlerAdapter());
	            }
	        });

        ChannelFuture future = connectRetry(bootstrap, HOST, PORT, MAX_RETRY);
        if(future == null) {
        	System.exit(0);
        }
        channel = ((ChannelFuture) future).channel();
	}
    
	private void send(String msg){
		channel.writeAndFlush(msg);
	}
	
	protected ChannelFuture connectRetry(Bootstrap bootstrap, String host, int port, int retry) {
        try {
        	return bootstrap.connect(HOST, PORT).sync();
		} catch (Exception e) {
			retry --;
			if(retry <= 0) {
				logger.error("Connect Netty Error", e);
				return null;
			}
			logger.info("retry");
			return connectRetry(bootstrap, host, port, retry);
		}
    }
    
	public static void main(String[] args) throws InterruptedException {
		NettyImClient client = new NettyImClient();
		client.init();

		client.send("hi i am client.");
	}
}
